(function($){
	
	var KEY = "jforest.timer";
	/*
		参数：displayEl : true|false //是否显示定时器
	*/
	var Timer = function(element,options){
		this.$element = $(element);
		this.options = $.extend({},{
			callback:function(){},
			active:true,
			interval:10,
			intervalTime:1000,
			displayEl:true,
			className:''
		},options);
		if(this.options.intervalTime < 1000){
			this.options.interval = 1;
			this.options.displayEl = false;
		}
		this.currentSecond = this.options.interval;
		if(this.options.displayEl){this._createEl();}
		this.reset();
	}
	
	Timer.prototype = {
		_createEl:function(){
			var self = this,options = this.options;
			self.$timeEl = $('<div class="'+options.className+'"><input type="checkbox" style="margin:0 3px 3px 0;"><span>'+self.currentSecond+'秒后刷新</span></div>');
			self.$element.append(self.$timeEl);
			self.$timeEl.find('[type="checkbox"]').click(function(){
				options.active = $(this).prop('checked');
			}).prop('checked',options.active);
		},
		reset:function(){
			var self = this,options = this.options;
			if(self.timer){
				clearInterval(timer);
				delete self.timer;
			}
			self.currentSecond = self.options.interval;
			//更新
			self.timer = setInterval(function(){
				if(options.active){
					self.currentSecond--;
					if(self.currentSecond < 0){
						self.currentSecond = options.interval;
					}
					if(self.currentSecond == 0){
						options.callback.apply(self);
					}
					if(options.displayEl){
						self.$timeEl.find('span').html(self.currentSecond + '秒后刷新');
					}
				}
				
			},options.intervalTime);
		},
		//如果参数为空则重置时间间隔
		setInterval:function(val){
			if(val){this.options.interval = val;}
			this.currentSecond = this.options.interval;
			if(this.options.displayEl){
				this.$timeEl.find('span').html(this.currentSecond + '秒后刷新');
			}
		},
		refresh:function(){
			this.options.callback.apply(this);
		},
		close:function(){
			this.options.active = false;
			if(this.options.displayEl){
				this.$timeEl.find('[type="checkbox"]').prop('checked',this.options.active);
			}
		},
		open:function(){
			this.options.active = true;
			if(this.options.displayEl){
				this.$timeEl.find('[type="checkbox"]').prop('checked',this.options.active);
			}
		}
	}
	
	$.fn.jfTimer = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				$this.data(KEY,new Timer(this,opts)); //创建控件
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
				if(entity === undefined){return;}
				value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfTimer.Constructor = Timer;
	
})(window.jQuery);